package com.i2works.smartluolong.web.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.i2works.smartluolong.utils.base.*;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.DAOException;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.dal.flow.dao.IFlowInfoDAO;
import com.i2works.smartluolong.web.entity.cart.CartReceiveDO;
import com.i2works.smartluolong.web.entity.company.CompanyApplyDO;
import com.i2works.smartluolong.web.entity.company.CompanyApplyImagesDO;
import com.i2works.smartluolong.web.entity.company.CompanyApplyMemberDO;
import com.i2works.smartluolong.web.entity.flow.FlowInfoDO;
import com.i2works.smartluolong.web.entity.flow.FlowProcessDO;
import com.i2works.smartluolong.web.entity.user.UserAccountDO;
import com.i2works.smartluolong.web.entity.user.UserAccountQuery;
import com.i2works.smartluolong.web.service.cart.ICartReceiveService;
import com.i2works.smartluolong.web.service.company.ICompanyApplyImagesService;
import com.i2works.smartluolong.web.service.company.ICompanyApplyMemberService;
import com.i2works.smartluolong.web.service.company.ICompanyApplyService;
import com.i2works.smartluolong.web.service.flow.IFlowProcessService;
import com.i2works.smartluolong.web.service.user.IPhp2JavaService;
import com.i2works.smartluolong.web.service.user.IUserAccountService;
import com.xiaoleilu.hutool.collection.CollUtil;
import com.xiaoleilu.hutool.http.HttpRequest;
import com.xiaoleilu.hutool.http.HttpResponse;
import com.xiaoleilu.hutool.http.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/11/17 10:36
 */

@Service("php2JavaService")
public class Php2JavaServiceImpl implements IPhp2JavaService {

    @Autowired
    private ICompanyApplyService companyApplyService;

    @Autowired
    private ICompanyApplyMemberService companyApplyMemberService;

    @Autowired
    private ICompanyApplyImagesService companyApplyImagesService;

    @Autowired
    private IFlowProcessService flowProcessService;

    @Autowired
    private IFlowInfoDAO flowInfoDAO;

    @Autowired
    private ICartReceiveService cartReceiveService;

    @Autowired
    private IUserAccountService userAccountService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result php2java(List<JSONObject> jsonObjectList) throws ServiceException {
        if (CollUtil.isEmpty(jsonObjectList)) {
            return R.success("完成所有转换");
        }
        Integer myid = 0;
        try {
            for (JSONObject json : jsonObjectList) {
                //原始申请ID
                Integer applyId = json.getInteger("applyId");
                myid = applyId;
                //用户
                JSONObject userObj = json.getObject("user", JSONObject.class);
                String phone = userObj.getString("mobile");
                //代办人
                UserAccountQuery userAccountQuery = new UserAccountQuery();
                userAccountQuery.setPhone(phone);
                Integer queryCheck = userAccountService.queryCheck(userAccountQuery);

//                String legalPhone = userObj.getString("legalMobile");
//                //法人
//                UserAccountQuery legalAccountQuery = new UserAccountQuery();
//                legalAccountQuery.setPhone(legalPhone);
//                Integer legalCheck = userAccountService.queryCheck(legalAccountQuery);
//

                UserAccountDO user = new UserAccountDO();
                //如果法人和代办人手机号，都存在账号。就使用代办人的。
                if (queryCheck > 0) {
                    user = userAccountService.queryLoginUser(phone);
                } else {
                    user.setPhone(phone);
                    user.setAvatar(AppConstant.UPLOAD_IMAGE_NOTPIC);
                    user.setCategory(13);
                    user.setOpenId("0");
                    user.setOpenId("0");
                    user.setLoginIp("127.0.0.1");
                    user.setStatus(1);
                    user.setPassword("ll" + user.getPhone());
                    user.setEmail(user.getPhone() + "@qq.com");
                    user.setUserName(user.getPhone());
                    user.setRealName(user.getPhone());
                    user.setCreateName(user.getPhone());
                    user.setUpdateName(user.getPhone());
                    userAccountService.save(user);
                }

                //基本信息
                CompanyApplyDO company = json.getObject("company", CompanyApplyDO.class);
                company.setUserId(user.getId());
                company.setUpdateName(user.getPhone());
                company.setCreateName(user.getPhone());
                company.setUpdateTime(company.getCreateTime());
                companyApplyService.save(company);
                Date dateTime = company.getCreateTime();
                //股东
                List<CompanyApplyMemberDO> shareHolderList = formatJsonList(json.getJSONArray("shareHolderList"), CompanyApplyMemberDO.class);
                if (CollUtil.isNotEmpty(shareHolderList)) {
                    for (CompanyApplyMemberDO memberDO : shareHolderList) {
                        memberDO.setApplyId(company.getId());
                        memberDO.setCreateName(user.getUserName());
                        memberDO.setUpdateName(user.getUserName());
                        memberDO.setCreateTime(dateTime);
                        memberDO.setUpdateTime(dateTime);
                        companyApplyMemberService.save(memberDO);
                    }
                }

                //查询办理人员
                List<CompanyApplyMemberDO> memberList = formatJsonList(json.getJSONArray("memberList"), CompanyApplyMemberDO.class);
                if (CollUtil.isNotEmpty(memberList)) {
                    for (CompanyApplyMemberDO memberDO : memberList) {
                        memberDO.setApplyId(company.getId());
                        memberDO.setCreateName(user.getUserName());
                        memberDO.setUpdateName(user.getUserName());
                        memberDO.setCreateTime(dateTime);
                        memberDO.setUpdateTime(dateTime);
                        companyApplyMemberService.save(memberDO);
                    }
                }

                //企业住所地的租赁协议或房产证照片
                List<String> imageList = formatJsonList(json.getJSONArray("imageList"), String.class);
                if (CollUtil.isNotEmpty(imageList)) {
                    for (String image : imageList) {
                        CompanyApplyImagesDO imagesDO = new CompanyApplyImagesDO();
                        imagesDO.setApplyId(company.getId());
                        imagesDO.setImg(image);
                        imagesDO.setCreateName(user.getUserName());
                        imagesDO.setUpdateName(user.getUserName());
                        imagesDO.setCreateTime(dateTime);
                        imagesDO.setUpdateTime(dateTime);
                        companyApplyImagesService.save(imagesDO);
                    }
                }

                //添加工作流
                FlowInfoDO flowInfoDO = new FlowInfoDO();

                //如果状态是4（核准通过），设置状态为已完成
                if (company.getApplyStatus().equals(CompanyStatusEnum.STATUS_4.getKey())) {
                    flowInfoDO.setComplete(FlowConstant.complete.TRUE);
                    //添加签发认领表信息
                    CartReceiveDO cartReceiveDO = new CartReceiveDO();
                    cartReceiveDO.setItemId(company.getId());
                    cartReceiveDO.setItemName(company.getCompanyName());
                    cartReceiveDO.setItemUserId(company.getUserId());
                    cartReceiveDO.setItemType(FlowItemTypeEnum.COMPANY_APPLY.getKey());
                    cartReceiveDO.setReceiveStatus(1);
                    cartReceiveDO.setReceiveUserId("-");
                    cartReceiveDO.setReceiveUserName(user.getUserName());
                    cartReceiveDO.setReceiveDatetime(dateTime);
                    cartReceiveDO.setReceiveIdcard("-");
                    cartReceiveDO.setIssueStatus(1);
                    cartReceiveDO.setIssueUserId(1);
                    cartReceiveDO.setIssueDatetime(dateTime);
                    cartReceiveDO.setStatus(GlobalConstant.status.TRUE);
                    cartReceiveDO.setUpdateName(company.getUpdateName());
                    cartReceiveDO.setCreateName(company.getUpdateName());
                    cartReceiveDO.setCreateTime(dateTime);
                    cartReceiveDO.setUpdateTime(dateTime);
                    cartReceiveService.save(cartReceiveDO);
                } else {
                    flowInfoDO.setComplete(0);
                }

                //添加工作流
                flowInfoDO.setItemId(company.getId());
                flowInfoDO.setItemName(company.getCompanyName() + "-" + FlowItemTypeEnum.COMPANY_APPLY.getValue());
                flowInfoDO.setItemType(FlowItemTypeEnum.COMPANY_APPLY.getKey());
                flowInfoDO.setItemStatus(CompanyStatusEnum.STATUS_1.getKey());
                flowInfoDO.setUserId(user.getId());
                flowInfoDO.setUpdateName(user.getUserName());
                flowInfoDO.setCreateName(user.getUserName());
                flowInfoDO.setCreateTime(dateTime);
                flowInfoDO.setUpdateTime(dateTime);
                flowInfoDO.setMessage("用户《" + flowInfoDO.getUpdateName() + "》提交审核");

                flowInfoDAO.save(flowInfoDO);


                //审批记录
                JSONArray list = json.getJSONArray("flowProcessList");
                if (CollUtil.isNotEmpty(list)) {
                    List<FlowProcessDO> flowProcessList = formatJsonList(list, FlowProcessDO.class);
                    if (CollUtil.isNotEmpty(flowProcessList)) {
                        for (FlowProcessDO flowProcess : flowProcessList) {
                            flowProcess.setItemId(company.getId());
                            flowProcess.setItemTitle(company.getCompanyName() + "-" + FlowItemTypeEnum.COMPANY_APPLY.getValue());
                            if (StringUtils.isBlank(flowProcess.getMessage())) {
                                flowProcess.setMessage("用户《" + user.getUserName() + "》提交审核");
                            }
                            flowProcess.setCreateName(user.getUserName());
                            flowProcess.setUpdateName(user.getUserName());
                            flowProcess.setUpdateTime(flowProcess.getCreateTime());
                            flowProcessService.save(flowProcess);
                        }
                    }
                }
                HttpRequest post = HttpUtil.createGet("http://127.0.0.1:8080/php2java/updateStatus/" + applyId);
                HttpResponse execute = post.execute();
                if (execute.getStatus() == HttpStatus.SC_OK) {
                    System.err.println("原始编号：" + applyId + "，新的编号：" + company.getId() + "，公司：" + company.getCompanyName() + "，状态更改完成....");
                }
                System.err.println("原始编号：" + applyId + "，新的编号：" + company.getId() + "，公司：" + company.getCompanyName() + "，数据导入完成....");
            }
            return R.success();
        } catch (DAOException e) {
            e.printStackTrace();
            System.err.println("原始编号：" + myid + "异常");
        }
        return R.error();
    }

    private <T> List<T> formatJsonList(JSONArray jsonArray, Class<T> clazz) {
        List<T> list = Lists.newArrayList();
        for (Object obj : jsonArray) {
            String string = JSONObject.toJSONString(obj);
            T object = JSON.parseObject(string, clazz);
            list.add(object);
        }
        return list;
    }
}
